package gold.digger;

import java.util.*;
import java.util.List;

/**
 * Created by fanzhenyu02 on 2020/6/27.
 * common problem solver template.
 */
public class LC1439 {
    public long startExecuteTime = System.currentTimeMillis();


    /*
     * @param 此题目参考了别人代码
     * 这是因为问题情况较为复杂
     * 未来需要再次复习此道题目
     * 厉害，BFS和最小堆结合，不愧是hard难度
     * @return:
     */
    class Solution {
        public int kthSmallest(int[][] mat, int k) {
            int sum = 0;
            for (int i = 0; i < mat.length; i++) sum += mat[i][0];

            PriorityQueue<Node> pq = new PriorityQueue<>((o1, o2) -> o1.total - o2.total);

            Set<String> visit = new HashSet<>();
            Node first = new Node(new int[mat.length], sum);
            visit.add(Arrays.toString(first.pick));
            pq.offer(first);

            while (k > 1) {
                Node item = pq.poll();

                for (int i = 0; i < mat.length; i++) {
                    item.pick[i]++;

                    if (item.pick[i] < mat[i].length && !visit.contains(Arrays.toString(item.pick))) {
                        visit.add(Arrays.toString(item.pick));
                        int[] pick = Arrays.copyOf(item.pick, item.pick.length);

                        int total = item.total - mat[i][item.pick[i] - 1] + mat[i][item.pick[i]];
                        pq.add(new Node(pick, total));
                    }

                    item.pick[i]--;
                }
                k--;
            }

            return pq.peek().total;
        }

        private class Node {
            private int[] pick;
            private int total;

            public Node(int[] pick, int total) {
                this.pick = pick;
                this.total = total;
            }
        }
    }

    public void run() {
        Solution solution = new Solution();
        List<Integer> list = new ArrayList<>();
        System.out.println(solution.toString());
    }

    public static void main(String[] args) throws Exception {
        LC1439 an = new LC1439();
        an.run();

        System.out.println("\ncurrent solution total execute time: " + (System.currentTimeMillis() - an.startExecuteTime) + " ms.");
    }
}
